#include <stdio.h>
#include <string>
#include <iostream>

#include "lua.hpp"
#include "LuaBridge.h"

#ifdef WIN32
#include "mylib.h"
#include "test.h"
#include "bridgelib.h"
extern int luaopen_student (lua_State* tolua_S);
#endif

#include "bridge_test.h"



int main(int argc, char** argv)
{

//	for (int i = 0; i < 2; ++i)
	lua_State* L = luaL_newstate();
	luaL_openlibs(L);

#ifdef WIN32
	luaL_requiref(L, "mylib", luaopen_mylib, 0);
	luaL_requiref(L, "test", luaopen_test, 0);
	luaL_requiref(L, "btest", luaopen_btest, 0);
	luaL_requiref(L, "student", luaopen_student, 0);
#endif
	BridgeTest btest;
//	luabridge::setGlobal(L, &btest, "test_b");

	unsigned long long roleid = ((unsigned long long)1 << 62);
	printf("sizeof: %d\n", sizeof(roleid));
	printf("sizeof: %d\n", sizeof(lua_Integer));
	luabridge::getGlobalNamespace(L);
//	luabridge::setGlobal(L, roleid, "roleid");
	lua_pushinteger(L, lua_Integer(roleid));
	lua_setglobal(L, "roleid");
		

	int ret = luaL_loadfile(L, "haha.lua");
	if (ret)
	{
		printf("load error: %d %s\n", ret, lua_tostring(L, -1));
		return -1;
	}
	ret = lua_pcall(L, 0, 0, 0);
	if (ret)
	{
		printf("pcall error: %d %s\n", ret, lua_tostring(L, -1));
		getchar();
		return -1;
	}

	/*
	lua_getglobal(L, "str");
	std::string str = lua_tostring(L, -1);
	printf("str: %s\n", str.c_str());

	lua_getglobal(L, "tbl");
	printf("ret = %d\n", ret);
	lua_getfield(L, -1, "name");
	if (lua_isstring(L, -1))
	{
		str = std::string(lua_tostring(L, -1));
		lua_pop(L, 1);
		printf("str: %s\n", str.c_str());
	}
	lua_getfield(L, -1, "id");
	int type = lua_type(L, -1);
	lua_Integer id = lua_tointeger(L, -1);
	printf("id =%lld\n", id);
	lua_pop(L, 1);

	lua_pushstring(L, "lll");
	lua_setfield(L, -2, "name");
	lua_getfield(L, -1, "name");
	str = std::string(lua_tostring(L, -1));
	lua_pop(L, 1);
	printf("str: %s\n", str.c_str());
	*/

	/*
	lua_getglobal(L, "add");
	lua_pushinteger(L, 10);
	lua_pushinteger(L, 20);
	lua_pcall(L, 2, 1, 0);
	lua_Integer v = lua_tointeger(L, -1);
	printf("v = %lld\n", v);
	*/


	/*
	printf("ret: %d\n", ret);
	printf("%d\n", sizeof(lua_Integer));


	lua_newtable(L);
	lua_setglobal(L, "t");
	lua_getglobal(L, "t");
	lua_pushstring(L, "Give me a girl friend");
	lua_setfield(L, -2, "title");
	lua_getfield(L, -1, "title");
	str = lua_tostring(L, -1);
	printf("title:%s\n", str.c_str());

	{
		luabridge::LuaRef f = luabridge::getGlobal(L, "add");
		try
		{
			luabridge::LuaRef r = f(10, 200);
			r.print(std::cout);
			lua_Integer result = r.cast<lua_Integer>();
			printf ("result: %d\n", result);
		}
		catch (luabridge::LuaException const& e)
		{
			printf("error: %s\n", e.what());
		}
	}
	*/



	getchar();
	lua_close(L);
	getchar();
	getchar();
	return 0;
}
